package com.lagou.cl;

import com.lagou.cl.pojo.*;
import com.lagou.cl.servlet.AbstractHttpServlet;

import java.io.IOException;
import java.net.Socket;
import java.util.List;
import java.util.Map;


public class RequestProcessor extends Thread {

	private Socket accept;
	private Map<String, AbstractHttpServlet> servletMap;

	private MappedHost mappedHost;

	public RequestProcessor(Socket accept, Map<String, AbstractHttpServlet> servletMap) {
		this.accept = accept;
		this.servletMap = servletMap;
	}

	public RequestProcessor(Socket accept, MappedHost mappedHost) {
		this.accept = accept;
		this.mappedHost = mappedHost;
	}

	public RequestProcessor(Socket accept, List<MappedHost> mappedHosts) {
		this.accept = accept;
	}

	@Override
	public void run() {
		try {
			if (null != servletMap && servletMap.size() > 0) {
				//获取输入数据
				Request request = new Request(accept.getInputStream());

				Response response = new Response(accept.getOutputStream());

				AbstractHttpServlet httpServlet = servletMap.get(request.getUrl());
				if (httpServlet == null) {
					response.outHtml(request.getUrl());
				} else {
					httpServlet.service(request, response);
				}

				response.outHtml(request.getUrl());
			}


			if (null != mappedHost) {
				Request request = new Request(accept.getInputStream());
				Response response = new Response(accept.getOutputStream());

				MappedContext context = null;
				for (MappedContext mappedContext : mappedHost.getMappedContexts()) {
					//上下文路径<Context docBase="web_demo" path="/web1"/>
					// /web1
					String contextPath = mappedContext.getName();
					if (contextPath.substring(1).equals(request.getUrl().split("/")[1])) {
						context = mappedContext;
						break;
					}
				}
				if (context != null) {
					MappedWrapper wrapper = null;
					List<MappedWrapper> exactWrappers = context.getExactWrappers();
					for (MappedWrapper mappedWrapper : exactWrappers) {
						String url = mappedWrapper.getName();
						if (url.equals(request.getUrl())) {
							wrapper = mappedWrapper;
							break;
						}
					}

					if (null != wrapper) {
						AbstractHttpServlet httpServlet = (AbstractHttpServlet) wrapper.getObject();
						if (httpServlet == null) {
							response.outHtml(request.getUrl());
						} else {
							httpServlet.service(request, response);
						}

						response.outHtml(request.getUrl());
					}else {
						response.outHtml(request.getUrl());
					}
				}else {
					response.outHtml(request.getUrl());
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				accept.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
